﻿using System;
using System.Linq;
using System.ServiceProcess;
using System.Reflection;
using System.Configuration.Install;
using Sustainalytics.Utils;

namespace Sustainalytics.Synchronization.Service
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            var debugMode = false;

            if (args.Length > 0)
            {
                foreach (var arg in args)
                {
                    switch (arg.ToLowerInvariant())
                    {
                        case "/debug":
                            debugMode = true;
                            break;
                        case "/install":
                            InstallService();
                            return;
                        case "/uninstall":
                            UninstallService();
                            return;
                    }
                }
            }

            AssemblyUtility.LoadAssembliesFromBin("Sustainalytics.GCCS.CompanyReportSyncStep.dll");
            AssemblyUtility.LoadAssembliesFromBin("Sustainalytics.CompanyReportSyncStep.dll");
            AssemblyUtility.LoadAssembliesFromBin("Sustainalytics.ClientDW.Synchronization.dll");
            AssemblyUtility.LoadAssembliesFromBin("Sustainalytics.Universes.Synchronization.dll");
            AssemblyUtility.LoadAssembliesFromBin("Sustainalytics.ESGRatings.BusinessLogic.dll");
            AssemblyUtility.LoadAssembliesFromBin("Sustainalytics.ProductInvolvement.BL.dll");
            AssemblyUtility.LoadAssembliesFromBin("Sustainalytics.ScreeningTool.Synchronization.dll");
            AssemblyUtility.LoadAssembliesFromBin("Sustainalytics.Governance.Synchronization.dll");
            AssemblyUtility.LoadAssembliesFromBin("Sustainalytics.Cluster.SyncStep.dll");

            if (debugMode || Environment.UserInteractive)
            {
                // start as console app
                ProgramConsole.Start();
            }
            else
            {
                // start as windows service
                ProgramWindowsService.Start();
            }            
        }

        private static bool IsServiceInstalled()
        {
            return ServiceController.GetServices().Any(s => s.ServiceName == WindowsService.Name);
        }

        private static void InstallService()
        {
            if (IsServiceInstalled())
            {
                UninstallService();
            }

            ManagedInstallerClass.InstallHelper(new[] { Assembly.GetExecutingAssembly().Location });
        }

        private static void UninstallService()
        {
            ManagedInstallerClass.InstallHelper(new[] { "/u", Assembly.GetExecutingAssembly().Location });
        } 
    }
}
